import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../widgets/platform/adaptive_button.dart';
import '../../widgets/platform/adaptive_text_field.dart';
import '../../widgets/platform/adaptive_card.dart';
import '../../widgets/database/db_test_widget.dart';
import '../../../data/services/db_connection_manager.dart';

/// 数据库连接配置页面
/// 允许用户配置MySQL、PostgreSQL、SQL Server、SQLite或MariaDB连接
class DbConnectionPage extends ConsumerStatefulWidget {
  final Function(Map<String, dynamic>)? onConnectionSaved;

  const DbConnectionPage({super.key, this.onConnectionSaved});

  @override
  ConsumerState<DbConnectionPage> createState() => _DbConnectionPageState();
}

class _DbConnectionPageState extends ConsumerState<DbConnectionPage> {
  final _formKey = GlobalKey<FormState>();
  final _hostController = TextEditingController();
  final _portController = TextEditingController();
  final _databaseController = TextEditingController();
  final _usernameController = TextEditingController();
  final _passwordController = TextEditingController();
  final _connectionNameController = TextEditingController();

  // 数据库类型选项
  final List<Map<String, dynamic>> _dbTypes = [
    {'value': 'mysql', 'label': 'MySQL', 'defaultPort': '3306'},
    {'value': 'postgresql', 'label': 'PostgreSQL', 'defaultPort': '5432'},
    {'value': 'sqlserver', 'label': 'SQL Server', 'defaultPort': '1433'},
    {'value': 'sqlite', 'label': 'SQLite', 'defaultPort': ''},
    {'value': 'mariadb', 'label': 'MariaDB', 'defaultPort': '3306'},
  ];

  String _selectedDbType = 'mysql';
  bool _obscurePassword = true;
  final bool _isTestingConnection = false;
  bool _isSaving = false;

  @override
  void initState() {
    super.initState();
    // 设置默认端口
    _portController.text = _dbTypes
        .firstWhere((db) => db['value'] == _selectedDbType)['defaultPort'];
  }

  @override
  void dispose() {
    _hostController.dispose();
    _portController.dispose();
    _databaseController.dispose();
    _usernameController.dispose();
    _passwordController.dispose();
    _connectionNameController.dispose();
    super.dispose();
  }

  /// 测试数据库连接
  Future<void> _testConnection() async {
    // 这个方法现在由DbTestWidget处理，这里保持空实现以避免错误
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const SelectableText('数据库连接配置'),
        backgroundColor: Colors.blue.shade50,
        foregroundColor: Colors.blue.shade700,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () => Navigator.of(context).pop(),
        ),
      ),
      body: SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Form(
            key: _formKey,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 页面说明
                AdaptiveCard(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      const SelectableText(
                        '配置数据库连接',
                        style: TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      const SizedBox(height: 8),
                      SelectableText(
                        '支持 MySQL、PostgreSQL、SQL Server、SQLite 和 MariaDB 数据库',
                        style: TextStyle(
                          color: Colors.grey.shade600,
                          fontSize: 14,
                        ),
                      ),
                    ],
                  ),
                ),

                const SizedBox(height: 24),

                // 数据库类型选择
                _buildDbTypeSelector(),

                const SizedBox(height: 16),

                // 连接配置表单
                _buildConnectionForm(),

                const SizedBox(height: 24),

                // 数据库连接测试组件
                DbTestWidget(
                  connectionConfig: {
                    'name': _connectionNameController.text,
                    'type': _selectedDbType,
                    'host': _hostController.text,
                    'port': _portController.text,
                    'database': _databaseController.text,
                    'username': _usernameController.text,
                    'password': _passwordController.text,
                  },
                ),

                // 操作按钮
                _buildActionButtons(),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildDbTypeSelector() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const SelectableText(
          '数据库类型',
          style: TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.w500,
          ),
        ),
        const SizedBox(height: 8),
        SegmentedButton<String>(
          segments: _dbTypes
              .map((db) => ButtonSegment<String>(
                    value: db['value'] as String,
                    label: SelectableText(db['label'] as String),
                  ))
              .toList(),
          selected: <String>{_selectedDbType},
          onSelectionChanged: (Set<String> newSelection) {
            _onDbTypeChanged(newSelection.first);
          },
        ),
      ],
    );
  }

  /// 构建连接配置表单
  Widget _buildConnectionForm() {
    return AdaptiveCard(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const SelectableText(
            '连接信息',
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.w500,
            ),
          ),
          const SizedBox(height: 16),

          // 连接名称
          AdaptiveTextField(
            controller: _connectionNameController,
            labelText: '连接名称',
            hintText: '为这个连接起个名字',
            validator: (value) {
              if (value == null || value.isEmpty) {
                return '请输入连接名称';
              }
              return null;
            },
          ),
          const SizedBox(height: 16),

          // 主机地址和端口
          Row(
            children: [
              Expanded(
                flex: 3,
                child: AdaptiveTextField(
                  controller: _hostController,
                  labelText: '主机地址',
                  hintText: 'localhost 或 IP 地址',
                  validator: (value) {
                    if (value == null || value.isEmpty) {
                      return '请输入主机地址';
                    }
                    return null;
                  },
                ),
              ),
              const SizedBox(width: 16),
              Expanded(
                flex: 1,
                child: AdaptiveTextField(
                  controller: _portController,
                  labelText: '端口',
                  hintText: '端口号',
                  keyboardType: TextInputType.number,
                ),
              ),
            ],
          ),
          const SizedBox(height: 16),

          // 数据库名称
          AdaptiveTextField(
            controller: _databaseController,
            labelText: '数据库名称',
            hintText: '请输入数据库名称',
            validator: (value) {
              if (value == null || value.isEmpty) {
                return '请输入数据库名称';
              }
              return null;
            },
          ),
          const SizedBox(height: 16),

          // 用户名
          AdaptiveTextField(
            controller: _usernameController,
            labelText: '用户名',
            hintText: '请输入数据库用户名',
            validator: (value) {
              if (value == null || value.isEmpty) {
                return '请输入用户名';
              }
              return null;
            },
          ),
          const SizedBox(height: 16),

          // 密码
          AdaptiveTextField(
            controller: _passwordController,
            labelText: '密码',
            hintText: '请输入数据库密码',
            obscureText: _obscurePassword,
            suffixIcon: IconButton(
              icon: Icon(
                _obscurePassword ? Icons.visibility : Icons.visibility_off,
              ),
              onPressed: () {
                setState(() {
                  _obscurePassword = !_obscurePassword;
                });
              },
            ),
            validator: (value) {
              if (value == null || value.isEmpty) {
                return '请输入密码';
              }
              return null;
            },
          ),
        ],
      ),
    );
  }

  Widget _buildActionButtons() {
    return Row(
      children: [
        Expanded(
          child: AdaptiveButton(
            onPressed: () => Navigator.of(context).pop(),
            isPrimary: false,
            child: const SelectableText('取消'),
          ),
        ),
        const SizedBox(width: 16),
        Expanded(
          child: AdaptiveButton(
            onPressed: _isTestingConnection ? null : _testConnection,
            child: _isTestingConnection
                ? const Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      SizedBox(
                        width: 16,
                        height: 16,
                        child: CircularProgressIndicator(strokeWidth: 2),
                      ),
                      SizedBox(width: 8),
                      SelectableText('测试中...'),
                    ],
                  )
                : const SelectableText('测试连接'),
          ),
        ),
        const SizedBox(width: 16),
        Expanded(
          child: AdaptiveButton(
            onPressed: _isSaving ? null : _saveConnection,
            isPrimary: true,
            child: _isSaving
                ? const Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      SizedBox(
                        width: 16,
                        height: 16,
                        child: CircularProgressIndicator(strokeWidth: 2),
                      ),
                      SizedBox(width: 8),
                      SelectableText('保存中...'),
                    ],
                  )
                : const SelectableText('保存配置'),
          ),
        ),
      ],
    );
  }

  /// 保存数据库连接配置
  Future<void> _saveConnection() async {
    if (!_formKey.currentState!.validate()) return;

    setState(() {
      _isSaving = true;
    });

    try {
      // 构建连接配置数据
      final connectionConfig = {
        'name': _connectionNameController.text,
        'type': _selectedDbType,
        'host': _hostController.text,
        'port': _portController.text,
        'database': _databaseController.text,
        'username': _usernameController.text,
        'password': _passwordController.text,
      };

      // 使用数据库连接管理器保存连接配置
      final dbManager = DbConnectionManager();
      await dbManager.saveConnection(DbConnectionConfig(
        id: DateTime.now().millisecondsSinceEpoch.toString(),
        name: _connectionNameController.text,
        host: _hostController.text,
        port: int.parse(_portController.text),
        database: _databaseController.text,
        username: _usernameController.text,
        password: _passwordController.text,
        type: _selectedDbType,
        createdAt: DateTime.now(),
      ));

      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: SelectableText('数据库连接配置已保存'),
            backgroundColor: Colors.green,
          ),
        );

        // 调用回调函数
        if (widget.onConnectionSaved != null) {
          widget.onConnectionSaved!(connectionConfig);
        }

        // 导航到表选择页面
        if (context.mounted) {
          Navigator.of(context).pushNamed(
            '/spreadsheet/tables',
            arguments: connectionConfig,
          );
        }
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: SelectableText('保存失败: ${e.toString()}'),
            backgroundColor: Colors.red,
          ),
        );
      }
    } finally {
      setState(() {
        _isSaving = false;
      });
    }
  }

  /// 数据库类型改变时的处理
  void _onDbTypeChanged(String? value) {
    if (value == null) return;

    setState(() {
      _selectedDbType = value;
      // 更新端口为默认值
      final dbType = _dbTypes.firstWhere((db) => db['value'] == value);
      _portController.text = dbType['defaultPort'];
    });
  }
}
